﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace csis.ImmediatorClasses
{
	/// <summary>
	/// Applies transformations that have been specified using csis preprocessor directives.
	/// </summary>
	public class ScriptTransformer
	{
		public ScriptTransformer(Script script, string[] lines)
		{
			if (script == null) throw new ArgumentNullException("script");
			if (lines == null) throw new ArgumentNullException("lines");

			this.script = script;
			this.lines = lines;
		}

		public static void TransformNew(Script script, string[] lines)
		{
			var transformer = new ScriptTransformer(script, lines);
			transformer.Transform();
		}

		private readonly Script script;
		private readonly string[] lines;

		public bool AnyTransformationsRequired()
		{
			return this.script.UseQuickHeader || this.script.AutoMain.HasValue;
		}

		public void Transform()
		{
			if (!this.AnyTransformationsRequired())
			{
				return;
			}

			IEnumerable<string> processedLines = this.lines;

			if (this.script.AutoMain.HasValue)
			{
				var simpleLineIndex = this.script.AutoMain.Value;
				var newContent = new List<string>(this.lines.Take(simpleLineIndex));
				
				newContent.Add(Properties.Resources.AutoMainTemplateStart);
				newContent.AddRange(this.lines.Skip(simpleLineIndex));
				newContent.Add(Properties.Resources.AutoMainTemplateEnd);

				processedLines = newContent;
			}

			if (this.script.UseQuickHeader)
			{
				var newContent = new List<string>();
				newContent.Add(Properties.Resources.QuickHeader);
				newContent.AddRange(processedLines);
				processedLines = newContent;
			}

			var temporaryScript = new TemporaryFile();
			File.WriteAllLines(temporaryScript.FileName, processedLines);

			this.script.TemporaryScript = temporaryScript;
		}
	}
}
